package com.ys.servers.user.verticle;

import com.ys.servers.common.mq.InternalEventData;
import com.ys.servers.common.util.CommonUtils;
import com.ys.servers.common.verticle.BasicRestfulVerticle;

import com.ys.servers.user.service.UserSignInfoService;
import com.ys.servers.user.service.impl.UserSignInfoServiceImpl;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;


/**
 * Created by taotao on 2017/5/24.
 */
public class UserVerticle extends BasicRestfulVerticle {

    private UserSignInfoService userSignInfoService;

    public static final String SERVICE_NAME = "user-service";

    private static final String USER_SIGNIN = "/sign";
    private static final String GET_USER_SIGNIN = "/:userId/:userType";

    public UserSignInfoService getUserSignInfoService() {
        return userSignInfoService;
    }

    public UserVerticle setUserSignInfoService(UserSignInfoService userSignInfoService) {
        this.userSignInfoService = userSignInfoService;
        return this;
    }

    @Override
    public void start(Future<Void> future) throws Exception {

        super.start();
        setUserSignInfoService(new UserSignInfoServiceImpl());

        final Router router = Router.router(vertx);
        // body handler
        router.route().handler(BodyHandler.create());
        // api route handler
        router.post(USER_SIGNIN).handler(this::userSign);
      /*  EventBusService.getProxy(discovery,
                new JsonObject().put("name", UserPointsService.SERVICE_NAME),
                future.completer());*/

        String host = config().getString("versions.rest.http.address", "0.0.0.0");
        int port = config().getInteger("versions.rest.http.port", 18889);

        // create HTTP server and publish REST service
        createHttpServer(router, host, port)
                .compose(serverCreated -> publishHttpEndpoint(SERVICE_NAME, host, port))
                .setHandler(future.completer());
    }

    private void userSign(RoutingContext context) {
        JsonObject paras = context.getBodyAsJson();
        String userId = paras.getValue("userId").toString();
        InternalEventData internalEventData = new InternalEventData().setApiName("add-points").setRecordAddress("points-service")
                .setParas(new JsonObject().put("userId", 1342543));
        interService(internalEventData).setHandler(restfulReturnDataHandler(context));
       /* interService(internalEventData).setHandler(res -> {
            Future<InternalEventData> dataFuture = Future.future();
            if (CommonUtils.validAsyncResult(res)) {
                resrestfulReturnDataHandler(context);
            } else {

            }
        });*/
    }

    @Override
    protected String interName() {
        return "inter-" + SERVICE_NAME;
    }

    @Override
    protected void initInternalDispatcher() {

    }
}
